window.onload = function () {
    var userName = getCookie('userName');
    var userPwd = getCookie('userPwd');
    if (!$.isEmptyObject(userName)) {
        $("#loginuser").val(userName)
    }
    if (!$.isEmptyObject(userPwd)) {
        $("#loginpwd").val(userPwd)
    }

    $('#loginpwd').bind('keypress', function (event) {
        if (event.keyCode == 13) {
            login();
        }
    })
}

var layer = '';
layui.use(['layer'], function () {
    layer = layui.layer;
});


function login() {
    var username = $("#loginuser").val();
    var password = $("#loginpwd").val();
    var role = $("#role").val();
    var isRememberPwd = $("#isRememberPwd").val();
    var param = {
        userName: username,
        passWord: password,
        role: role,
        isRememberPwd: isRememberPwd
    }
    // 检验表单参数
    var verifyResult = verify(param);
    if (verifyResult) {
        $.ajax({
            type: "POST",
            url: "/user/login",
            // contentType: "application/json",
            sync: true,
            data: param, //JSON.stringify(param)
            dataType: "json",
            success: function (result) {
                if (result.code == 200) {
                    top.location.href = "main";
                } else {
                    layer.msg(result.msg, {icon: 2, offset: '100px', time: 2000});
                }
            }
        });
    }
}

function logout() {
    // 检验表单参数
    $.ajax({
        type: "POST",
        url: "/user/logout",
        // contentType: "application/json",
        sync: true,
        data: null, //JSON.stringify(param)
        dataType: "json",
        success: function (result) {
            if (result.code == 200) {
                top.location.href = "login";
            } else {
                layer.msg(result.msg, {icon: 2, offset: '100px', time: 2000});
            }
        }
    });
}

// 校验用户名、密码
function verify(param) {
    var userName = param.userName;
    var passWord = param.passWord;

    if ($.isEmptyObject(userName)) {
        layer.msg('请填用户名！', {icon: 2, offset: '100px', time: 2000});
        return false;
    } else if ($.isEmptyObject(passWord)) {
        layer.msg('请填用户密码！', {icon: 2, offset: '100px', time: 2000});
        return false;
    }
    return true;
}

//name--value 要保存的键值对   expireDay---要保存的时间(天)
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) {
            return decodeURI(c.substring(name.length, c.length));
        }
    }
    return "";
}
